﻿using IMES.Common.Domain.KeepModel.ProductionFile;
using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using Keep.API.Common.L.Dtos;
using MediatR;

namespace Keep.API.Appliction.ProductionPlanFile
{
	/// <summary>
	/// 产品明细
	/// </summary>
	public class PlanProductDetailsListHandler : IRequestHandler<PlanProductDetailsListCommon, ResultPage<PlanProductDetailsDto>>
	{
		private readonly IFreeSql _freeSql;
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="freeSql"></param>
		public PlanProductDetailsListHandler(IFreeSql freeSql)
		{
			_freeSql = freeSql;
		}
		/// <summary>
		/// 产品明细
		/// </summary>
		public Task<ResultPage<PlanProductDetailsDto>> Handle(PlanProductDetailsListCommon request, CancellationToken cancellationToken)
		{
			var result = new ResultPage<PlanProductDetailsDto>() { Code = (int)CodeEnum.success, Messege = "查询成功" };
			var list = _freeSql.Select<PlanProductDetails, Product>()
				.InnerJoin((p, pd) =>  p.ProductNumber== pd.ProductNumber)
				 .WhereIf(!string.IsNullOrEmpty(request.DocumentNumber), (p, pd) => p.DocumentNumber == request.DocumentNumber)
				.ToList((p, pd) => new PlanProductDetailsDto()
				{
					ProductNumber = pd.ProductNumber,
					ProductName = pd.ProductName,
					OrderNo = p.OrderNo,
					Quantity = p.Quantity,
					CompletedQuantity = p.CompletedQuantity,
					ProductSpecification = pd.ProductSpecification,
					CreateName = p.CreateName,
					CreateDate = p.CreateDate,
					UpdateName = p.UpdateName,
					UpdateDate = p.UpdateDate,
				});
			result.totalCount = list.Count();
			result.totalPage = (int)Math.Ceiling(result.totalCount / (double)request.PageSize);
			result.Data = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

			return Task.FromResult(result);

		}
	}
}